package com.im.service.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.im.common.enums.exception.BaseErrorCode;
import com.im.common.enums.exception.GateWayErrorCode;
import com.im.common.enums.exception.BaseExceptionEnum;
import com.im.common.model.RestResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * 网关拦截器，用于在请求到达服务前进行身份验证
 */
@Component
public class GateWayInterceptor implements HandlerInterceptor {

    private static final String[] SWAGGER_PATHS = {"/swagger-resources", "/swagger-ui.html", "/v2/api-docs","/webjars","/doc.html"};

    @Autowired
    private IdentityCheck identityCheck;

    /**
     * 在请求到达服务前进行身份验证
     *
     * @param request  HttpServletRequest对象
     * @param response HttpServletResponse对象
     * @param handler  处理器对象
     * @return 是否继续处理请求
     * @throws Exception 异常
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 如果请求的路径中包含Swagger相关的路径，则返回true，表示放行
        String uri = request.getRequestURI();
        for (String path : SWAGGER_PATHS) {
            if (uri.contains(path)) {
                return true;
            }
        }
        // 获取appId 操作人 userSign
        String appIdStr = request.getParameter("appId");
        if (StringUtils.isBlank(appIdStr)) {
            // 如果appId为空，返回错误信息
            resp(RestResponse.error(GateWayErrorCode.APPID_NOT_EXIST), response);
            return false;
        }

        String identifier = request.getParameter("identifier");
        if (StringUtils.isBlank(identifier)) {
            // 如果操作人为空，返回错误信息
            resp(RestResponse.error(GateWayErrorCode.OPERATER_NOT_EXIST), response);
            return false;
        }

        String userSign = request.getParameter("userSign");
        if (StringUtils.isBlank(userSign)) {
            // 如果userSign为空，返回错误信息
            resp(RestResponse.error(GateWayErrorCode.USERSIGN_NOT_EXIST), response);
            return false;
        }

        // 签名和操作人和appId是否匹配
        BaseExceptionEnum baseExceptionEnum = identityCheck.checkUserSig(identifier, appIdStr, userSign);
        if (baseExceptionEnum != BaseErrorCode.SUCCESS) {
            // 如果签名和操作人和appId不匹配，返回错误信息
            resp(RestResponse.error(baseExceptionEnum), response);
            return false;
        }

        return true;
    }


    /**
     * 返回响应信息
     *
     * @param respVo   响应信息
     * @param response HttpServletResponse对象
     */
    private void resp(RestResponse respVo, HttpServletResponse response) {
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=utf-8");
        try {
            String resp = JSONObject.toJSONString(respVo);
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-type", "application/json;charset=UTF-8");
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Allow-Credentials", "true");
            response.setHeader("Access-Control-Allow-Methods", "*");
            response.setHeader("Access-Control-Allow-Headers", "*");
            response.setHeader("Access-Control-Max-Age", "3600");
            writer = response.getWriter();
            writer.write(resp);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (writer != null) {
                writer.checkError();
            }
        }
    }

}

